<?php

namespace app\api\Service;

use think\Db;
use think\Config;
use think\Response;
use app\common\library\Auth;

class StewardService
{
    // 获取特长列表
    public static function getForteList()
    {
        $list = Config::get('site.forte');
        $total = count($list);
        return ['code'=>1,'msg'=>'查询成功','data'=>['total'=>$total,'list'=>$list]];
    }

    // 申请管家
    public static function applySteward($data)
    {
        try{
            $auth = Auth::instance();
            $user_id = $auth->id;
            $data['gender'] = isset($data['gender']) && $data['gender']? $data['gender'] : 0;
            $data['type'] = isset($data['type']) && $data['type'] ? $data['type'] : 1;
            if(!$data['avatar']) return ['code'=>0, 'msg'=>'请上传头像','data'=>''];
            if(!$data['realname']) return ['code'=>0, 'msg'=>'请填写姓名','data'=>''];
            if( $data['gender'] != 1 && $data['gender'] != 0 ) return ['code'=>0, 'msg'=>'请选择性别','data'=>''];
            if(!$data['idcard_number']) return ['code'=>0, 'msg'=>'请填写身份证号','data'=>''];
            if(!$data['idcard_a']) return ['code'=>0, 'msg'=>'请上传身份证人像面','data'=>''];
            if(!$data['idcard_b']) return ['code'=>0, 'msg'=>'请上传身份证国徽面','data'=>''];
            if(!$data['age']) return ['code'=>0, 'msg'=>'请填写年龄','data'=>''];
            if(!$data['forte']) return ['code'=>0, 'msg'=>'请选择特长','data'=>''];
            if(!$data['brief']) return ['code'=>0, 'msg'=>'请填写年龄','data'=>''];
            if(!$data['honor']) return ['code'=>0, 'msg'=>'请上传荣誉证书','data'=>''];
            if(!$data['certificate']) return ['code'=>0, 'msg'=>'请上传资格证书','data'=>''];
//            if(!$data['not_crime']) return ['code'=>0, 'msg'=>'请上传无犯罪证明','data'=>''];

            $status = \app\admin\model\StewardApply::where(['user_id'=>$user_id, 'status'=>['in',['1','2']]])->value('status');
            if($status == 1) return ['code'=>0, 'msg'=>'不要重复申请','data'=>''];
            if($status == 2) return ['code'=>0, 'msg'=>'您已有管家身份','data'=>''];

            $invite = isset($data['invite']) && $data['invite'] ? $data['invite'] : '';

            if($invite){
                $firstChar = substr($invite, 0, 1);
                if($firstChar == 'U'){
                    $pid = 0;
                }
                if($firstChar == 'S'){
                    $pid = substr($invite, 1);
                    $parent = \app\admin\model\Steward::get($pid);
                    if(!$parent) return ['code'=>0,'msg'=>'邀请码不正确','data'=>''];
                }
            }else{
                $pid = 0;
            }

            $params = [
                'user_id' => $user_id,
                'type' => $data['type'],
                'avatar' => $data['avatar'],
                'realname' => $data['realname'],
                'gender' => $data['gender'],
                'idcard_number' => $data['idcard_number'],
                'idcard_a' => $data['idcard_a'],
                'idcard_b' => $data['idcard_b'],
                'age' => $data['age'],
                'forte' => $data['forte'],
                'brief' => $data['brief'],
                'honor' => $data['honor'],
                'certificate' => $data['certificate'],
                'not_crime' => $data['not_crime'],
            ];

            $is_id = \app\admin\model\StewardApply::where(['user_id'=>$user_id, 'status'=>3])->value('id');
            if($is_id){
                $params['status'] = 1;
                $params['reason'] = '';
                $result = \app\admin\model\StewardApply::where(['id'=>$is_id])->update($params);
            }else{
                $params['pid'] = $pid;
                $result = \app\admin\model\StewardApply::create($params);
            }


            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }
        if($result){
            return ['code'=>1,'msg'=>'操作成功','data'=>''];
        }else{
            return ['code'=>0,'msg'=>'操作失败','data'=>''];
        }
    }

    // 获取申请管家结果
    public static function getApplyStewardResult($data)
    {
        $user_id = $data['user_id'];

        $details = \app\admin\model\StewardApply::where(['user_id'=>$user_id])->field('createtime,updatetime',true)
            ->find();
        if($details) {
            $details['honor'] = explode(',', $details['honor']);
            $details['certificate'] = explode(',', $details['certificate']);
        }else{
            $details['status'] = '-1';
        }

        return ['code'=>1,'msg'=>'查询成功','data'=>$details];
    }

    // 获取管家列表
    public static function getStewardList($data)
    {
        $auth = Auth::instance();
        $user_id = $auth->id;
        $limit = isset($data['limit']) ? $data['limit'] : 10;

        $list = \app\admin\model\Steward::where(['status'=>'normal'])->order('createtime desc')->field('id,avatar,realname,gender,age,forte,brief')->paginate($limit)->toArray();
        foreach($list['data'] as &$item){
            $forte = explode(',', $item['forte']);
            $item['forte'] = [];
            if(count($forte) > 3){
                $x = 3;
            }else{
                $x = count($forte);
            }
            for($i = 0; $i < $x; $i++){
                $item['forte'][] = $forte[$i];
            }
            // 是否收藏字段
            if($user_id) {
                $is_collect = \app\admin\model\StewardCollect::where(['user_id'=>$user_id,'steward_id'=>$item['id']])->value('id');
                $item['is_collect'] = $is_collect? 1 : 0;
            }else{
                $item['is_collect'] = 0;
            }
        }
        return ['code'=>1,'msg'=>'查询成功','data'=>['total'=>$list['total'],'list'=>$list['data']]];
    }

    // 获取管家详情
    public static function getStewardDetails($data)
    {
        $id = $data['id'];
        $auth = Auth::instance();
        $user_id = $auth->id;
        if(!$id) return ['code'=>0,'msg'=>'无效参数','data'=>''];
        $details = \app\admin\model\Steward::where(['id'=>$id,'status'=>'normal'])->field('createtime,updatetime,status',true)
            ->find();
        $details['forte'] = explode(',', $details['forte']);
        $details['honor'] = explode(',', $details['honor']);
        $details['certificate'] = explode(',', $details['certificate']);

        if($user_id) {
            $is_collect = \app\admin\model\StewardCollect::where(['user_id'=>$user_id,'steward_id'=>$id])->value('id');
            $details['is_collect'] = $is_collect? 1 : 0;
        }else{
            $details['is_collect'] = 0;
        }
        return ['code'=>1,'msg'=>'查询成功','data'=>$details];
    }

    // 管家个人中心
    public static function stewardCenter($data)
    {
        $auth = Auth::instance();
        $steward_id = $auth->getStewardId();
        $data = \app\admin\model\Steward::where(['id'=>$steward_id])->field('id,avatar,realname,money,forte')->find();
        if($data){
            $data['forte'] = explode(',', $data['forte']);
            $data['is_steward'] = 1;
        }else{
            $data['is_steward'] = 0;
        }
        return ['code'=>1,'msg'=>'查询成功','data'=>$data];
    }

    // 管家收入明细
    public static function getMoneyLog($data)
    {
        $auth = Auth::instance();
        $steward_id = $auth->getStewardId();
        $limit = isset($data['limit']) ? $data['limit'] : 10;
        $list = \app\admin\model\StewardMoneyLog::where(['steward_id'=>$steward_id])->field('id,money,memo,createtime,relate_order')->paginate($limit)->each
            (function ($item){
            $item['createtime_text'] = date('Y-m-d H:i:s',$item['createtime']);
            return $item;
        });
        return ['code'=>1,'msg'=>'查询成功','data'=>$list];
    }

    // 管家累计收益
    public static function getAddUp($data)
    {
        $auth = Auth::instance();
        $steward_id = $auth->getStewardId();
        $limit = $data['limit'] ? $data['limit'] : 10;
        $start = $data['start'] ? strtotime($data['start'].' 00:00:00') : strtotime(date('Y-m-',time()).'01 00:00:00');
        $over = $data['over'] ? strtotime($data['over'].' 23:59:59') : strtotime(date('Y-m-d',time()). ' 23:59:59');
        if($start > $over) return ['code'=>0,'msg'=>'开始时间必须大于结束时间','data'=>''];

        $list = \app\admin\model\StewardMoneyLog::where(['steward_id'=>$steward_id,'relate_order'=>['<>',0]])->whereTime
        ('createtime','between',[$start,$over])->field('id,money,memo,createtime,relate_order')->paginate($limit)->each
        (function ($item){
            $item['createtime_text'] = date('Y-m-d H:i:s',$item['createtime']);
            return $item;
        });
        $total = \app\admin\model\StewardMoneyLog::where(['steward_id'=>$steward_id,'relate_order'=>['<>',0]])->whereTime
        ('createtime','between',[$start,$over])->sum('money');
        return ['code'=>1,'msg'=>'查询成功','data'=>['total'=>$total,'list'=>$list]];
    }

    // 管家提现
    public static function applyWithdrawal($data)
    {
        try{

            $auth = Auth::instance();
            $steward_id = $auth->getStewardId();
            $steward_money = \app\admin\model\Steward::where(['id'=>$steward_id])->value('money');
            if($steward_money < $data['money']) return ['code'=>0,'msg'=>'管家余额不足','data'=>''];

            $bank = \app\admin\model\StewardBank::get($data['bank_id']);
            if(!$bank) return ['code'=>0,'msg'=>'无效提现银行卡','data'=>''];

            $apply = \app\admin\model\StewardWithdraw::where(['steward_id' => $steward_id,'status'=>1])->value('id');
            if($apply) return ['code'=>0,'msg'=>'您已有一笔提现申请在审核，请不要重复申请','data'=>''];

            $params = [
                'steward_id' => $steward_id,
                'money' => $data['money'],
                'bank_id' => $data['bank_id'],
                'cardholder' => $bank['cardholder'],
                'bank' => $bank['bank'],
                'branch' => $bank['branch'],
                'cardnumber' => $bank['cardnumber']
            ];

            $result = \app\admin\model\StewardWithdraw::create($params);

            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }
        if($result){
            return ['code'=>1,'msg'=>'操作成功','data'=>''];
        }else{
            return ['code'=>0,'msg'=>'操作失败','data'=>''];
        }
    }

    // 提现账列表
    public static function getWithdrawalList($data)
    {
        $auth = Auth::instance();
        $steward_id = $auth->getStewardId();
        $limit = $data['limit'] ? $data['limit'] : 10;

        $list = \app\admin\model\StewardWithdraw::where(['steward_id'=>$steward_id])->field('id,money,reason,status,createtime')->paginate($limit)->each
        (function ($item){
            $item['createtime_text'] = date('Y-m-d H:i:s',$item['createtime']);
            return $item;
        });
        return ['code'=>1,'msg'=>'查询成功','data'=>$list];
    }

    // 提现账详情
    public static function getWithdrawalDetails($data)
    {
        $auth = Auth::instance();
        $steward_id = $auth->getStewardId();

        $details = \app\admin\model\StewardWithdraw::where(['steward_id'=>$steward_id,'id'=>$data['id']])->field('id,money,status,reason,createtime')->find();

        $details['createtime_text'] = date('Y-m-d H:i:s',$details['createtime']);

        return ['code'=>1,'msg'=>'查询成功','data'=>$details];
    }

    // 新增提现账户
    public static function addWithdrawAccount($data)
    {
        try{

            $auth = Auth::instance();
            $steward_id = $auth->getStewardId();

            $params = [
                'steward_id' => $steward_id,
                'cardholder' => $data['cardholder'],
                'bank' => $data['bank'],
                'branch' => $data['branch'],
                'cardnumber' => $data['cardnumber']
            ];
            $result = \app\admin\model\StewardBank::create($params);

            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }
        if($result){
            return ['code'=>1,'msg'=>'操作成功','data'=>''];
        }else{
            return ['code'=>0,'msg'=>'操作失败','data'=>''];
        }
    }

    // 编提现现账户
    public static function editWithdrawAccount($data)
    {
        try{

            $auth = Auth::instance();
            $steward_id = $auth->getStewardId();

            $params = [
                'steward_id' => $steward_id,
                'cardholder' => $data['cardholder'],
                'bank' => $data['bank'],
                'branch' => $data['branch'],
                'cardnumber' => $data['cardnumber']
            ];
            $result = \app\admin\model\StewardBank::where('id',$data['id'])->update($params);

            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }
        if($result){
            return ['code'=>1,'msg'=>'操作成功','data'=>''];
        }else{
            return ['code'=>0,'msg'=>'操作失败','data'=>''];
        }
    }

    // 提现现账户列表
    public static function getWithdrawAccountList($data)
    {
        $auth = Auth::instance();
        $steward_id = $auth->getStewardId();

        $limit = isset($data['limit']) ? $data['limit'] : 10;
        $list = \app\admin\model\StewardBank::where(['steward_id'=>$steward_id])->field('id,cardholder,bank,branch,cardnumber')->paginate($limit)->toArray();

        return ['code'=>1,'msg'=>'查询成功','data'=>$list];
    }

    // 删除提现现账户
    public static function delWithdrawAccount($data)
    {
        $id = $data['id'];
        if (!$id) return ['code' => 0, 'msg' => '无效参数', 'data' => ''];
        $result = \app\admin\model\StewardBank::destroy($id);
        if($result){
            return ['code'=>1,'msg'=>'操作成功','data'=>''];
        }else{
            return ['code'=>0,'msg'=>'操作失败','data'=>''];
        }
    }

    // 邀请排行
    public static function getShareRank($data)
    {
        $auth = Auth::instance();
        $steward_id = $auth->getStewardId();
        $list = \app\admin\model\Steward::where(['status'=>'normal'])->order('invite_award desc')->field('id,avatar,realname,invite_award')->limit(10)->select();
        if($list){
            foreach($list as $k => &$v){
                if($v['invite_award'] == 0){
                    unset($list[$k]);
                }
            }
        }else{
            $list = [];
        }
        return ['code'=>1,'msg'=>'查询成功','data'=>$list];
    }

    // 我的邀请
    public static function getShareMine($data)
    {
        $auth = Auth::instance();
        $steward_id = $auth->getStewardId();
        $limit = isset($data['limit']) ? $data['limit'] : 10;
        $list = \app\admin\model\Steward::where(['pid'=>$steward_id])->field('id,avatar,realname,createtime')
            ->paginate($limit)->each(function ($item){
//
            $money = Db::name('steward_money_log')->where(['steward_id'=>$item['id'],'createtime'=>$item['createtime']])->value('money');
            if($money){
                $item['award'] = $money;
            }else{
                $item['award'] = Config::get('site.steward_invite_money');
            }
            $item['createtime_text'] = date('Y-m-d H:i:s',$item['createtime']);
            unset($item['createtime']);
        });

        return ['code'=>1,'msg'=>'查询成功','data'=>$list];
    }

    // 获取分享二维码
    public static function getShareQr($data)
    {
        $auth = Auth::instance();
        $steward_id = $auth->getStewardId();

        $params['text'] = request()->domain() . "/h5?code=S{$steward_id}&type=1";

        $qrCode = \addons\qrcode\library\Service::qrcode($params);

        $mimetype = 'png' == 'png' ? 'image/png' : 'image/svg+xml';

        $response = Response::create()->header("Content-Type", $mimetype);

        // 直接显示二维码
        header('Content-Type: ' . $qrCode->getContentType());
        $response->content($qrCode->writeString());

        // 写入到文件

        $qrcodePath = ROOT_PATH . 'public/share/steward/';
        if (!is_dir($qrcodePath)) {
            @mkdir($qrcodePath);
        }
        if (is_really_writable($qrcodePath)) {
            $filePath = $qrcodePath . md5($steward_id) . '.png';
            $qrCode->writeFile($filePath);
        }
        $url = request()->domain() . '/share/steward/' . md5($steward_id) . '.png';

        // 邀请人数
        $steward = Db::name('steward')->where('id', $steward_id)->field('avatar,realname,brief')->find();

        return ['code'=>1,'msg'=>'获取成功','data'=>['url'=>$url, 'steward'=>$steward]];
    }



}